//
//  SHRegisterViewController.m
//  JiFengDaRen
//
//  Created by Lyc on 2017/12/11.
//  Copyright © 2017年 SH_iOS. All rights reserved.
//

#import "SHRegisterViewController.h"
#import "UIButton+WebCache.h"
#import "JCLoginViewModel.h"


@interface RegisterField : UITextField

@end

@implementation RegisterField

+ (RegisterField *)initWithPlaceholder:(NSString *)str{
    
    RegisterField * registerF = [RegisterField new];
    registerF.placeholder = str;
    registerF.backgroundColor = [UIColor whiteColor];

    [registerF setValue:[UIColor colorWithHexString:@"#999999"] forKeyPath:@"_placeholderLabel.textColor"];
    [registerF setValue:[UIFont systemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    registerF.font = [UIFont systemFontOfSize:14];
    registerF.clearButtonMode = UITextFieldViewModeWhileEditing;
    registerF.layer.masksToBounds = YES;
    registerF.layer.cornerRadius = 45/2;
    registerF.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 45)];
    registerF.leftViewMode = UITextFieldViewModeAlways;
    return registerF;
}


@end


@interface SHRegisterViewController ()<UITextFieldDelegate>

@property (nonatomic, strong) UIScrollView * scrollView;

@property (nonatomic, strong) RegisterField * phoneField;

@property (nonatomic, strong) RegisterField * gCodeField;//图形码

@property (nonatomic, strong) RegisterField * vCodeField;

@property (nonatomic, strong) RegisterField * psdField;

@property (nonatomic, strong) RegisterField * conPsdField;

@property (nonatomic, strong) RegisterField * inPhoneField;

@property (nonatomic, strong) UIButton * gCodeBtn;

@property (nonatomic, strong) UIButton * vCodeBtn;

@property (nonatomic, strong) UIButton * modifyBtn;

@property (nonatomic, strong) NSString * url;

@property (nonatomic, strong) NSString * ID;

@end

@implementation SHRegisterViewController


- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = YES;
    [super viewWillAppear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self getVerifyImgCode];

    self.view.backgroundColor = [UIColor colorWithHexString:@"#474E66"];
    UIImage * image = [UIImage imageNamed:@"register_img_new"];

    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, -KSTATUBARHEIGHT, KScreenWidth, KScreenHeight + KSTATUBARHEIGHT)];
    self.scrollView.contentSize = CGSizeMake(KScreenWidth, image.size.height);
    [self.view addSubview:self.scrollView];
    
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, image.size.height)];
    imageView.image = image;
    imageView.userInteractionEnabled = YES;
    [self.scrollView addSubview:imageView];
    
    UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"back_white"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(bacBtnkAction) forControlEvents:UIControlEventTouchUpInside];
    backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [imageView addSubview:backBtn];
    
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(imageView).offset(15);
        make.top.equalTo(imageView).offset(35);
        make.width.height.mas_offset(40);
    }];
    
    self.phoneField = [RegisterField initWithPlaceholder:@"中国大陆手机号"];
    self.phoneField.keyboardType = UIKeyboardTypeNumberPad;
    [imageView addSubview:self.phoneField];
    
    [self.phoneField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(imageView).offset(233+KSTATUBARHEIGHT);
        make.height.mas_offset(45);
        make.width.mas_offset(__I6Width(300));
        make.centerX.equalTo(imageView);
    }];
    
    self.gCodeField = [RegisterField initWithPlaceholder:@"请输入正确的图形码"];
    [imageView addSubview:self.gCodeField];
    
    [self.gCodeField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phoneField.mas_bottom).offset(15);
        make.height.mas_equalTo(self.phoneField.mas_height);
        make.width.mas_offset(__I6Width(190));
        make.left.equalTo(self.phoneField.mas_left);
    }];
    
    self.gCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.gCodeBtn.layer.masksToBounds = YES;
    self.gCodeBtn.layer.cornerRadius = 45/2;
    self.gCodeBtn.backgroundColor = [UIColor whiteColor];
    self.gCodeBtn.tag = 100;
    [self.gCodeBtn addTarget:self action:@selector(registerBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [imageView addSubview:self.gCodeBtn];
    
    [self.gCodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.phoneField.mas_right);
        make.height.mas_equalTo(self.phoneField.mas_height);
        make.left.equalTo(self.gCodeField.mas_right).offset(10);
        make.top.equalTo(self.gCodeField.mas_top);
    }];
    
    self.vCodeField = [RegisterField initWithPlaceholder:@"请输入验证码"];
    [imageView addSubview:self.vCodeField];
    
    [self.vCodeField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.gCodeField.mas_bottom).offset(15);
        make.left.right.height.mas_equalTo(self.gCodeField);
    }];
    
    self.vCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.vCodeBtn.layer.masksToBounds = YES;
    self.vCodeBtn.layer.cornerRadius = 45/2;
    self.vCodeBtn.backgroundColor = [UIColor whiteColor];
    [self.vCodeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
    [self.vCodeBtn setTitleColor:[UIColor colorWithHexString:@"#C28C42"] forState:UIControlStateNormal];
    self.vCodeBtn.titleLabel.font = KSHSystemFont(14);
    self.vCodeBtn.tag = 101;
    [self.vCodeBtn addTarget:self action:@selector(registerBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [imageView addSubview:self.vCodeBtn];
    
    [self.vCodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.equalTo(self.gCodeBtn);
        make.top.equalTo(self.vCodeField.mas_top);
    }];
    
    self.psdField = [RegisterField initWithPlaceholder:@"请输入密码"];
    self.psdField.secureTextEntry = YES;
    [imageView addSubview:self.psdField];
    
    [self.psdField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.vCodeField.mas_bottom).offset(15);
        make.left.right.height.mas_equalTo(self.phoneField);
    }];
    
    self.conPsdField = [RegisterField initWithPlaceholder:@"请确认密码"];
    self.conPsdField.secureTextEntry = YES;
    [imageView addSubview:self.conPsdField];
    
    [self.conPsdField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.psdField.mas_bottom).offset(15);
        make.left.right.height.mas_equalTo(self.phoneField);
    }];
    
    self.inPhoneField = [RegisterField initWithPlaceholder:@"请输入邀请人手机号"];
    self.inPhoneField.keyboardType = UIKeyboardTypeNumberPad;
    [imageView addSubview:self.inPhoneField];
    
    [self.inPhoneField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.conPsdField.mas_bottom).offset(15);
        make.left.right.height.mas_equalTo(self.phoneField);
    }];
    
    self.modifyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.modifyBtn setBackgroundImage:[UIImage imageNamed:@"btn_bg"] forState:UIControlStateNormal];
    [self.modifyBtn setTitle:@"立即注册" forState:UIControlStateNormal];
    self.modifyBtn.titleLabel.font = KSHSystemFont(16);
    [self.modifyBtn setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:UIControlStateNormal];
    self.modifyBtn.tag = 102;
    [self.modifyBtn addTarget:self action:@selector(registerBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [imageView addSubview:self.modifyBtn];
    
    [self.modifyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.phoneField);
        make.top.equalTo(self.inPhoneField.mas_bottom).offset(35);
    }];
}

- (void)bacBtnkAction{
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)registerBtnAction:(UIButton *)btn{
    [self.view endEditing:YES];

    if (btn.tag == 100) {
        [self getVerifyImgCode];
    }else if (btn.tag == 101){
        if (self.phoneField.text.length == 0) {
            [self.view makeToast:@"请输入手机号" duration:1 position:@"center"];
            return;
        }
        if (![Tool isMobileNumber:self.phoneField.text]) {
            [self.view makeToast:@"手机号格式不正确" duration:1 position:@"center"];
            return;
        }
        if (self.gCodeField.text.length == 0) {
            [self.view makeToast:@"请输入图形码" duration:1 position:@"center"];
            [self getVerifyImgCode];
            return;
        }
        [self startTime];
        [self sendVerifyImgCode];
    }else{
        if (self.phoneField.text.length == 0) {
            [self.view makeToast:@"请输入手机号" duration:1 position:@"center"];
            return;
        }
        if (self.vCodeField.text.length == 0) {
            [self.view makeToast:@"请输入验证码" duration:1 position:@"center"];
            return;
        }
        if (self.psdField.text.length == 0) {
            [self.view makeToast:@"请设置密码" duration:1 position:@"center"];
            return;
        }
        if ( self.psdField.text.length < 6 || self.psdField.text.length > 18) {
            [self.view makeToast:@"请输入6—18位密码" duration:1 position:@"center"];
            return;
        }
        if (self.conPsdField.text.length == 0) {
            [self.view makeToast:@"请再次输入密码" duration:1 position:@"center"];
            return;
        }
        if (![self.psdField.text isEqualToString:self.conPsdField.text]) {
            [self.view makeToast:@"两次输入的密码不一致！" duration:1 position:@"center"];
            return;
        }
        if (self.inPhoneField.text == 0) {
            [self.view makeToast:@"请输入邀请人手机号！" duration:1 position:@"center"];
            return;
        }
        if (![Tool isMobileNumber:self.phoneField.text]) {
            [self.view makeToast:@"手机号格式不正确" duration:1 position:@"center"];
            return;
        }
        if (![Tool isMobileNumber:self.inPhoneField.text]) {
            [self.view makeToast:@"邀请人手机号格式不正确" duration:1 position:@"center"];
            return;
        }
        if ([self.inPhoneField.text isEqualToString:self.phoneField.text]) {
            [self.view makeToast:@"注册手机号不能与邀请人手机号相同" duration:1 position:@"center"];
            return;
        }
        [self getUserRegister];
    }
}

- (void)startTime{
    __block int timeout=30; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t  _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [self.vCodeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                self.vCodeBtn.userInteractionEnabled = YES;
            });
        }else{
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                
                [self.vCodeBtn setTitle:[NSString stringWithFormat:@"%@S",strTime] forState:UIControlStateNormal];
                self.vCodeBtn.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
    
}

#pragma mark --- 文本框代理
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

#pragma mark - 网络请求
// 获取图形码
- (void)getVerifyImgCode{
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [JCLoginViewModel getVerifyImgCodeSuccess:^(NSDictionary *result) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        self.url = result[@"data"][@"url"];
        self.ID = result[@"data"][@"id"];
        [self.gCodeBtn sd_setImageWithURL:[NSURL URLWithString:self.url] forState:UIControlStateNormal];
    }];
}

// 发送图形验证码
- (void)sendVerifyImgCode{
    
    NSDictionary *dict = @{@"phone":self.phoneField.text,@"id":self.ID,@"user_code":self.gCodeField.text};
    
    [JCLoginViewModel sendImgCodeParams:dict Success:^(NSDictionary *dict) {
        
        if ([dict[@"success"] boolValue] == YES) {
            [self.view makeToast:@"验证码发送成功!" duration:1 position:@"center"];
        }else{
            [self.view makeToast:dict[@"data"] duration:1 position:@"center"];
        }
    }];
}

// 注册的接口
- (void)getUserRegister{
    
    NSDictionary *dict = @{@"phone":self.phoneField.text,
                           @"password":self.psdField.text,
                           @"verify_code":self.vCodeField.text,
                           @"inviter_phone":self.inPhoneField.text
                           };
    
    [JCLoginViewModel userRegisterParams:dict Success:^(id result) {
        
        if ([result[@"success"] boolValue] == YES) {
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            [Tool setObject:self.phoneField.text forKey:@"ID"];
            [Tool setObject:self.psdField.text forKey:@"PSW"];
            [self.view makeToast:@"注册成功" duration:1 position:@"center"];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        }else{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [self.view makeToast:result[@"data"] duration:1 position:@"center"];
        }
        
    }];
}

@end
